package br.com.hotel68.dao;

import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import br.com.hotel68.model.Room;
import br.com.hotel68.model.RoomType;

public class BaseDAO {

	private static EntityManagerFactory emf;
	private static EntityManager em;

	public static void init() {
		emf = Persistence.createEntityManagerFactory("Hotel68Database");
		em = emf.createEntityManager();
	}

	// somente para testes, remover depois
	public void testDatabase() {

		Room room = em.find(Room.class, 1);
		if (room != null) {
			System.out.printf("Room %d, type %s%n", room.getId(), room.getType());
		} else {
			System.out.println("Room not found, creating an example...");
			room = new Room(1, "Quarto1", RoomType.MASTER);
			EntityTransaction tx = em.getTransaction();
			tx.begin();
			em.persist(room);
			tx.commit();
		}

	}

	public static <T> Collection<T> findAll(Class<T> c) {
		// return em.createQuery("SELECT o FROM " + c.getName() + " o").getResultList();
		CriteriaQuery<T> q = em.getCriteriaBuilder().createQuery(c);
		Root<T> r = q.from(c);
		return em.createQuery(q.select(r)).getResultList();
	}

	public static <T> T findById(Class<T> c, Object id) {
		return em.find(c, id);
	}
	
	public static <T> void insertById(Class<T> c, Object id){
		em.getTransaction().begin();
		em.persist(id);
		em.getTransaction().commit();
		em.close();
	}

}
